#include <cerrno>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "error.hpp"
using namespace std;

void usage(string proc)
{
    cout << "usage \n\t" << proc << "serverip serverport" << endl;
}

int main(int argc, char *argv[])
{
    // cout << "hello tcp_client" << endl;
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }
    string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    // 1.创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);

    // 要不要bind？要bind，但不是自己bind，由os自动帮我们bind
    // 何时bind？第一次由用户态进入内核态时，进行bind
    // 不要listen,更不要accept
    // 2.建立连接，与服务器建立连接
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    int cnt = 5;
    while (true)
    {
        int n = connect(sock, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
            cout <<"你还能重新连接" << --cnt << "次" << endl;
        else
            break;
        if (cnt == 0)
            break;
        sleep(1);
    }

    if (cnt)
    {
        // 连接成功
        cout << "accept success..." << endl;
        char buff[1024] = {0};
        while (true)
        {

            // 1.传送数据
            string line;
            cout << "enter>>>";
            getline(cin, line);
            write(sock,line.c_str(),line.size());

            // 2.获取数据
            ssize_t n = read(sock, buff, sizeof(buff) - 1);
            if (n > 0)
            {
                buff[n] = 0;
                cout << serverip << "-" << serverport << ">>>" << buff << endl;
            }
            else if (n == 0)
            {
                // 这里也是同理，对端如果关闭，这里会读到0
                close(sock);
                cout << serverip << "-" << serverport << "close, me too" << endl;
                break;
            }
            else
            {
                cout << "read failed" << strerror(errno) << endl;
                exit(READ_ERR);
            }
        }
    }
    else
    {
        cerr << "accept failed..." << strerror(errno) << endl;
        exit(ACCEPT_ERR);
    }
    return 0;
}